package com.uddenberg.wt;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import com.uddenberg.wt.dbdefinitions.DailyDataDefinition.DailyDataColumns;
import com.uddenberg.wt.helpers.GeneralHelper;

import android.app.ActivityGroup;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class InsertDailyActivity extends ActivityGroup {

	private static final String TAG = "InsertDailyActivity";
	
	private Button btnGeneral;
	private RadioButton rbNo;
	private Button btnSave;
	
	private static TextView txtDate;
	private static TextView txtSleepStartTime;
	private static TextView txtSleepEndTime;
	private static TextView txtExerciseStartTime;
	private static TextView txtExerciseEndTime;
	private static RatingBar rbQuality;
	private static RatingBar rbIntensity;
	private static RadioButton rbSickYes;

	private static int mSleepStartHour;
    private static int mSleepStartMinute;
    private static int mSleepEndHour;
    private static int mSleepEndMinute;
    private static int mExerciseStartHour;
    private static int mExerciseStartMinute;
    private static int mExerciseEndHour;
    private static int mExerciseEndMinute;
    private static boolean mExerciseChanged = false;
    private static int mYear;
    private static int mMonth;
    private static int mDay;
    
    
    static final int SLEEP_START_ID = 0;
    static final int SLEEP_END_ID = 1;
    static final int DATE_ID = 2;
    static final int EXERCISE_START_ID = 3;
    static final int EXERCISE_END_ID = 4;
    
    private Uri mUri;
    
    private static final String[] PROJECTION = new String[] {
    	DailyDataColumns._ID, // 0
    	DailyDataColumns.DATE, // 1
    };
    
    
    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSleepStartSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mSleepStartHour = hourOfDay;
                mSleepStartMinute = minute;
                updateTime(SLEEP_START_ID);
            }
        };
        
    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSleepEndSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mSleepEndHour = hourOfDay;
                mSleepEndMinute = minute;
                updateTime(SLEEP_END_ID);
            }
        };
     
    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeExerciseStartSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mExerciseStartHour = hourOfDay;
                mExerciseStartMinute = minute;
                mExerciseChanged = true;
                updateTime(EXERCISE_START_ID);
            }
        };
        
    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeExerciseEndSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mExerciseEndHour = hourOfDay;
                mExerciseEndMinute = minute;
                mExerciseChanged = true;
                updateTime(EXERCISE_END_ID);
            }
        };
	
    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDate();
                }
            };
	
            
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.icontext: Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
	                            break;
	    }
	    return true;
	}        
            
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        View viewToLoad = LayoutInflater.from(this.getParent()).inflate(R.layout.insertdaily_header, null);
        setContentView(viewToLoad);
        
        // If no data was given in the intent (because we were started
        // as a MAIN activity), then use our default content provider.
        Intent intent = getIntent();
        if (intent.getData() == null) {
            intent.setData(DailyDataColumns.CONTENT_URI);
        }
        
        mUri = intent.getData();
        
        // Perform a managed query. The Activity will handle closing and requerying the cursor
        // when needed.
        @SuppressWarnings("unused")
		Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null, null,
        		DailyDataColumns.DEFAULT_SORT_ORDER);
        
        
        // Set the "No" (sick) radio button selected as default
        rbNo = (RadioButton)findViewById(R.id.daily_radio_sick_no);
        rbNo.setChecked(true);
            
        
        
        txtSleepStartTime = (TextView)findViewById(R.id.daily_edittext_sleep_start);
        txtSleepEndTime = (TextView)findViewById(R.id.daily_edittext_sleep_end);
        txtDate = (TextView)findViewById(R.id.daily_edittext_date);
        txtExerciseStartTime = (TextView)findViewById(R.id.daily_txt_exercise_start);
        txtExerciseEndTime = (TextView)findViewById(R.id.daily_txt_exercise_end);
        
     	// get the current date, set default sleep start (22:00) and sleep end (08:00)
        final Calendar c = Calendar.getInstance();
        mSleepStartHour = 22;
        mSleepStartMinute = 0;
        mSleepEndHour = 8;
        mSleepEndMinute = 0;
        mExerciseStartHour = 13;
        mExerciseStartMinute = 0;
        mExerciseEndHour = 13;
        mExerciseEndMinute = 0;
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        
        updateTime(SLEEP_START_ID);
        updateTime(SLEEP_END_ID);
        updateDate();
        updateTime(EXERCISE_START_ID);
        updateTime(EXERCISE_END_ID);
        
        
        
        btnSave = (Button)findViewById(R.id.daily_save);
        btnSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				ContentValues values = new ContentValues();
				
				// The date
				final Calendar cal = Calendar.getInstance();
		    	cal.set(Calendar.MONTH, mMonth);
		    	cal.set(Calendar.DAY_OF_MONTH, mDay);
		    	cal.set(Calendar.YEAR, mYear);
				values.put(DailyDataColumns.DATE, cal.getTimeInMillis()/1000);
				
				// Exercise
				if(true == mExerciseChanged) {
					// User has changed the start or end time for the exercise
					
					// Set the hours and minute of START
					cal.set(Calendar.HOUR_OF_DAY, mExerciseStartHour);
					cal.set(Calendar.MINUTE, mExerciseStartMinute);
					values.put(DailyDataColumns.EXERCISE_START, cal.getTimeInMillis()/1000);
					
					// Set the hours and minute of END
					cal.set(Calendar.HOUR_OF_DAY, mExerciseEndHour);
					cal.set(Calendar.MINUTE, mExerciseEndMinute);
					values.put(DailyDataColumns.EXERCISE_END, cal.getTimeInMillis()/1000);
				}
				
				// Sleep WAKE UP
				cal.set(Calendar.HOUR_OF_DAY, mSleepEndHour);
				cal.set(Calendar.MINUTE, mSleepEndMinute);
				values.put(DailyDataColumns.SLEEP_END, cal.getTimeInMillis()/1000);
				
				// Sleep WENT TO SLEEP
				// Change the date back one day
				if(mSleepStartHour > 12) {
					// If you go to bed at 12:00-00:00 it was the day before
					// if you go to bed at 02:00 we should not roll back one day
					cal.roll(Calendar.DAY_OF_MONTH, -1);
				}
				cal.set(Calendar.HOUR_OF_DAY, mSleepStartHour);
				cal.set(Calendar.MINUTE, mSleepStartMinute);
				values.put(DailyDataColumns.SLEEP_START, cal.getTimeInMillis()/1000);
				
				// Quality of the sleep
				rbQuality = (RatingBar)findViewById(R.id.daily_ratbar_quality);
				values.put(DailyDataColumns.QUALITY, rbQuality.getRating());
				
				// Intensity of the exercise
				rbIntensity = (RatingBar)findViewById(R.id.daily_ratbar_intensity);
				values.put(DailyDataColumns.INTENSITY, rbIntensity.getRating());
				
				// Sick?
				rbSickYes = (RadioButton)findViewById(R.id.daily_radio_sick_yes);
				if(rbSickYes.isSelected()) {
					values.put(DailyDataColumns.SICK, 1);
				} else {
					values.put(DailyDataColumns.SICK, 0);
				}
				
				
				// Continue save the record
				CharSequence text;
				Uri newUri = null;
				try {
					newUri = getContentResolver().insert(mUri, values);
	            } catch (Exception e) {
	            	Log.e(TAG, e.getMessage());
	            }
				if(newUri == null) {
					text = "Unable to save post";
				} else {
					text = "Saved!";
					
					// Reset all Ratbars and dates
					rbIntensity.setRating(0);
					rbQuality.setRating(0);
					rbNo.setSelected(true);
					mExerciseChanged = false;
					
					c.setTime(new Date());  
					mYear = c.get(Calendar.YEAR);
					mMonth = c.get(Calendar.MONTH);
					mDay = c.get(Calendar.DAY_OF_MONTH);
					mSleepStartHour = 22;
			        mSleepStartMinute = 0;
			        mSleepEndHour = 8;
			        mSleepEndMinute = 0;
			        mExerciseStartHour = 13;
			        mExerciseStartMinute = 0;
			        mExerciseEndHour = 13;
			        mExerciseEndMinute = 0;
					
			        updateTime(SLEEP_START_ID);
			        updateTime(SLEEP_END_ID);
			        updateTime(EXERCISE_START_ID);
					updateTime(EXERCISE_END_ID);
					updateDate();
					
				}
	            Context context = getApplicationContext();
	            int duration = Toast.LENGTH_LONG;

	            Toast toast = Toast.makeText(context, text, duration);
	            toast.show();
			}
        });
        
        
        
        
        
        btnGeneral = (Button)findViewById(R.id.daily_general_insert_button);
        btnGeneral.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				InsertGroupActivity.group.back();
			}
		});
        
        // Add a click listener to the time and date textview
        txtDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!isFinishing()) {
					showDialog(DATE_ID);
				}
			}
        });
        txtSleepStartTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!isFinishing()) {
					showDialog(SLEEP_START_ID);
				}
			}
        });
        txtSleepEndTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!isFinishing()) {
					showDialog(SLEEP_END_ID);
				}
			}
        });
        txtExerciseStartTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!isFinishing()) {
					showDialog(EXERCISE_START_ID);
				}
			}
        });
        txtExerciseEndTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!isFinishing()) {
					showDialog(EXERCISE_END_ID);
				}
			}
        });
        
    }
    
    private static void updateTime(int id) {
    	switch(id) {
    	case SLEEP_START_ID:
    		txtSleepStartTime.setText(
    		        new StringBuilder()
    	                .append(GeneralHelper.pad(mSleepStartHour)).append(":")
    	                .append(GeneralHelper.pad(mSleepStartMinute)));
    	case SLEEP_END_ID:
    		txtSleepEndTime.setText(
    		        new StringBuilder()
    	                .append(GeneralHelper.pad(mSleepEndHour)).append(":")
    	                .append(GeneralHelper.pad(mSleepEndMinute)));
    	case EXERCISE_START_ID:
    		txtExerciseStartTime.setText(
    		        new StringBuilder()
    	                .append(GeneralHelper.pad(mExerciseStartHour)).append(":")
    	                .append(GeneralHelper.pad(mExerciseStartMinute)));
    	case EXERCISE_END_ID:
    		txtExerciseEndTime.setText(
    		        new StringBuilder()
    	                .append(GeneralHelper.pad(mExerciseEndHour)).append(":")
    	                .append(GeneralHelper.pad(mExerciseEndMinute)));

    	}
    	
    }
    
    private static void updateDate() {
    	final Calendar cal = Calendar.getInstance();
    	cal.set(Calendar.MONTH, mMonth);
    	cal.set(Calendar.DAY_OF_MONTH, mDay);
    	cal.set(Calendar.YEAR, mYear);
    	 
    	String text = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault())
    			.format(cal.getTime());
    	txtDate.setText(text);
    }
    
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case SLEEP_START_ID:
            return new TimePickerDialog(InsertGroupActivity.group,
                    mTimeSleepStartSetListener, mSleepStartHour, mSleepStartMinute, true);
        case SLEEP_END_ID:
        	return new TimePickerDialog(InsertGroupActivity.group,
                    mTimeSleepEndSetListener, mSleepEndHour, mSleepEndMinute, true);
        case DATE_ID:
            return new DatePickerDialog(InsertGroupActivity.group,
            		mDateSetListener, mYear, mMonth, mDay);
        case EXERCISE_START_ID:
            return new TimePickerDialog(InsertGroupActivity.group,
                    mTimeExerciseStartSetListener, mExerciseStartHour, mExerciseStartMinute, true);
        case EXERCISE_END_ID:
        	return new TimePickerDialog(InsertGroupActivity.group,
                    mTimeExerciseEndSetListener, mExerciseEndHour, mExerciseEndMinute, true);
        }
        
        return null;
    }
    
	
}
